package com.sen.controller;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sen.dao.UserDao;
import com.sen.entity.DruginfoEntity;
import com.sen.entity.SellEntity;
import com.sen.entity.SellheadEntity;
import com.sen.entity.UserEntity;
import com.sen.service.SellService;
import com.sen.service.SellheadService;
import com.sen.service.UserService;
import com.sen.service.WarehouseService;
import com.sen.utils.CommTimer;
import com.sen.utils.R;
import com.sen.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.alipay.api.AlipayConstants.*;

/**
 * 销售信息表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-01-08 17:54:40
 */
@RestController
@RequestMapping("sell")
public class SellController {
    @Autowired
    private SellService sellService;
    @Autowired
    private SellheadService sellheadService;
    @Autowired
    private UserDao userDao;
    @Autowired
    CommTimer commTimer;
    @Autowired
    WarehouseService warehouseService;
    /**
     * 出售药品通过订单号获取雪花算法
     */
    @RequestMapping("/uuid")
    public R uuid() {
        return R.ok().put("uuid",new SnowflakeIdWorker(0,0).nextId());
    }

    /**
     * 获取用户优惠价格
     * @param money
     * @return
     */
    @RequestMapping("/getmoney")
    public R getmoney(Double money,String state){
        Double discount = sellService.getmoney(money,state);
        return R.ok().put("discount", discount);
    }
    @RequestMapping("/phoneChange")
    public R phoneChange(String phone){
        UserEntity user = userDao.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
        if (user != null) {
            return R.ok().put("msg", "可用").put("uid",user.getUid());
        }
        else {
            return R.ok().put("msg", "会员手机号不可用");
        }
    }

    /**
     * 修改订单同时减去库存
     * @param sid
     */
    @RequestMapping("/updCount")
    public void updCount(String sid){
        //获取所有出售商品
        List<SellEntity> sells = sellService.list(new QueryWrapper<SellEntity>().eq("sid", sid));
        //修改订单状态为已支付
        boolean update = sellheadService.update(new UpdateWrapper<SellheadEntity>().set("state", 0).eq("sid", sid));
        //判断为是否重复订单
        if (update){
            for (SellEntity sell : sells) {
                //获取商品的出售量
                Integer count = sell.getCount();
                //获取仓库批次号
                Integer lno = sell.getLno();
                //减少仓库数量
                warehouseService.updCount(count,lno);
            }
        }
    }

    /**
     * 支付宝沙箱支付
     * @param httpResponse
     * @param money 总钱数
     * @param uuid 订单号
     * @param goods 商品列表
     * @param uid 购买客户id
     * @throws IOException
     */
    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse,String money,String uuid,String eid,String goods,String uid) throws IOException {
        final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbtHTC+fCXGE21escDxeSk+WruocXKHVOQrTxv9hMcKEBKRg5WLkWWEUmE6J/7/fX9RzQz7gDcNlbio3Pc84rB7NFGEGsvos+pWCdrpOVZMsMcUez9BAxiTOPEmmRZK9m6+/qxjNIQIJ3wC6W4kyLfAFCsx/rEk5aAbgR2f93eXXvuhkvDCJ7yHLHpkKz+vOuL0vljbJWz9ZZTRdyd4VfPqrsY1BEu1aUQWXn3jpxAZxDfbbKb26DlWZifQJtBs4dtb9cMu856dpUEtQFDzrn6kAf/KJ209w51uBWS1wnlOPv77C7x4zk85cyJMKRToyOR3GFdRChSVs28OXR1yB4PAgMBAAECggEABO9CKA+9xTwa8l5ywjbaWTQiZG+yEga96D7lRHMbBfBsoS35NFgBEpF3sAOjVlwlGKLSD7dCRbhfJo2hlWYOhrjXpQ3OJ9NUG3zUuv+d2SbXsiUSiq4/KjpfmZJ/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X0+SnvNm6HTMjy7d9jCzvlofM8GWFf962LIVUzF4/MLvtrD76RMtf+kgWUFaMx3uT0AAOTLAJbw9AmK0dYDiAwQKLMFtaDv7TeR8Lt0FKreU83vtlubMfm1kmqDf5NHaRTncLfwIDAQAB+k7F2Te7vBwuv0Imz1xjv/FHRCZ2AyhWg4PzPuikAkQB9KMAv5J5+DXE6oDZVTDkdlass/4xj8bmNoeOCUBA3okHaBI0WSzNb69Nt4C1eZNZYMmKBSeWMmFxfGaAe+HO8qEiKLkHK6q+WLaM55/GCuqKRof8xi7AqUATgpePzBmX0+SnvNm6HTMjy7d9jCzvlofM8GWFf962LIVUzF4/MLvtrD76RMtf+kgWUFaMx3uT0AAOTLAJbw9AmK0dYDiAwQKLMFtaDv7TeR8Lt0FKreU83vtlubMfm1kmqDf5NHaRTncLfwIDAQAB";
        final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, "2021000116676880", APP_PRIVATE_KEY, "json", "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl("http://localhost:9527/druginfo/queryAll");
        //需要外网
        request.setNotifyUrl("http://localhost/sell/test");

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = uuid;
        //付款金额，必填
        String total_amount = money;
        //订单名称，必填
        String subject ="瑞茂药房";
        //商品描述，可空

        String body = "药品出售";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            //通过序列化取出所有商品
            List<DruginfoEntity> drugs = JSON.parseArray(goods, DruginfoEntity.class);
            /*for (DruginfoEntity drug : drugs) {
                System.out.println("drug = " + drug);
            }*/
            //添加详细订单默认为未支付
            sellService.addOrder(uuid,drugs);
            //添加订单表头
            sellService.addOrderHeader(uuid,eid,money,uid);

            //添加定时任务
            commTimer.orderClose(uuid);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + "UTF-8");
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}
